//
//  ESLocationSupport.m
//  EasyStyle
//
//  Created by FK on 16/4/7.
//  Copyright © 2016年 FK. All rights reserved.
//

#import "ESLocationSupport.h"
#import <CoreLocation/CoreLocation.h>

@interface ESLocationSupport ()<CLLocationManagerDelegate>

@property (nonatomic,retain) CLLocationManager* locationManager;
@property (nonatomic,retain) CLLocation *location;

@end

@implementation ESLocationSupport


+ (ESLocationSupport *)sharedInstance{
    static ESLocationSupport *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [ESLocationSupport new];
    });
    return manager;
}
+ (CLLocation *)currentLocation{
    return [self sharedInstance].location;
}
+ (BOOL)denied{
    
    NSLog(@"%d",[CLLocationManager authorizationStatus]);
    return [CLLocationManager locationServicesEnabled] == NO ||[CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied;
}
- (void)dealloc{
    self.locationManager = nil;
    [self.locationManager startUpdatingLocation];
}

- (void)startUpdatingLocation{
    if (self.locationManager) {
        [self stopUpdatingLocation];
    }
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
        [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways ||
        [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        
        if (!self.locationManager) {
            self.locationManager = [[CLLocationManager alloc] init];
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
            //self.locationManager.purpose = @"To provide functionality based on user's current location.";
            if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [self.locationManager requestWhenInUseAuthorization];
            }
        }
        
        [self.locationManager startUpdatingLocation];
        self.location = [self.locationManager location];
    }
}
- (void)stopUpdatingLocation{
    if (self.locationManager) {
        [self.locationManager stopUpdatingLocation];
        self.locationManager.delegate = nil;
        self.locationManager = nil;
    }
}

#pragma mark CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{

    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    if (currentLocation) {
        if (self.location == nil) {
            //            [[NSNotificationCenter defaultCenter] postNotificationName:DidUpdateLocationsNotification object:nil];
        }
        self.location = currentLocation;
    }
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            //将获得的所有信息显示到label上
            NSLog(@"%@",placemark.name);
            
            //获取城市
            NSString *city = placemark.locality;
            
            if (!city) {
                // 四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            self.cityName = city;
            NSLog(@"获取城市------%@", self.cityName);
            
            ESDataController *shareInstance = [ESDataController shareInstance];
            [shareInstance saveUserCityName:city];
            [[NSNotificationCenter defaultCenter]postNotificationName:LocationSupportUpdateWeatherNotification object:city];
            
        }else if (error == nil && [array count] == 0){
            
            NSLog(@"No results were returned.");
            
        }else if (error != nil){
            
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
    [self stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        [self stopUpdatingLocation];
    }
    
    if (status == kCLAuthorizationStatusDenied) {
        
    }
}

@end
